<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\TableDataChangeModel;
use share\exception\ApiException;
use share\service\BaseModelService;

class TableDataChangeService extends BaseModelService
{

    public static function getModel()
    {
        return new TableDataChangeModel;
    }

    /**
     * 编辑条目 新增或者修改
     */
    public static function edit($info)
    {
        $id = $info['id'];
        unset($info['id']);
        if ($id == 0) {
            self::addTableDataChange($info);
        } else {
            self::updateTableDataChange($id, $info);
        }
        //TODO add code here after data change
        return $info;
    }

    /**
     * 新增条目
     */
    public static function addTableDataChange($info)
    {
        //TODO add code here  
        self::add($info);
    }

    public static function addOrUpdate($db,$table,$day,$num){
        $origin = self::getByFilter([
            'db'=>$db,
            'table_name' => $table,
            'day' => $day,
        ]);
        if($origin){
            if($origin['num'] != $num){
                self::update($origin['id'],[
                    'num' => $num,
                ]);
            }
        }
        else{
            self::add([
                'db'=>$db,
                'table_name' => $table,
                'day' => $day,
                'num' => $num,
            ]);
        }
    }

    /**
     * 修改条目
     */
    public static function updateTableDataChange($id, $info)
    {
        $origin  = self::getBase($id);
        if (empty($origin)) {
            throw new ApiException("origin data is not exists", ErrnoPlus::COMMON_INVALID_INPUT);
        }
        //TODO  add code here  

        self::update($id, $info);
    }

    /**
     * 删除条目
     */
    public static function delById($id)
    {
        $origin = self::getBase($id);
        if (empty($origin)) {
            return;
        }
        //TODO  add code here  
        $res = self::del($id);
        return $res;
    }

    /**
     * 页面查询条件
     */
    public static function buildCondition($filter)
    {
        $res = [];
        if (isset($filter['db']) && !empty($filter['db'])) {
            $res['db'] = ['like', '%' . $filter['db'] . '%'];
        }
        if (isset($filter['table_name']) && !empty($filter['table_name'])) {
            $res['table_name'] = ['like', '%' . $filter['table_name'] . '%'];
        }
        return $res;
    }
}
